<script>
	import { onMount } from 'svelte';
	import ShopItem from './ShopItem.svelte'; // 导入ShopItem组件
	import { Notyf } from 'notyf';

	let userData = {};
	let currentPage = 'shop'; // 默认显示商城页面
	let shops = [];
	let notyf;

	let currentTime = '';

	onMount(() => {
		// getCurrentTime();
		console.log(currentTime);
		const storedUserData = localStorage.getItem('userData');
		if (storedUserData) {
			userData = JSON.parse(storedUserData);
		} else {
			console.error('No user data found in localStorage.');
		}
		notyf = new Notyf({
			duration: 2000,
			position: {
				x: 'right',
				y: 'top'
			}
		});

		// 检查是否已经刷新过
		if (!sessionStorage.getItem('refreshed')) {
			sessionStorage.setItem('refreshed', 'true');
			window.location.reload();
		} else {
			sessionStorage.removeItem('refreshed');
		}
		//initializeShops();
		getShops();
		refreshBackgroundImage();
	});

	// function initializeShops() {
	// 	// 初始化测试数据
	// 	shops = [
	// 		{ name: 'Shop 1', image: '/beach.png' },
	// 		{ name: 'Shop 2', image: '/bluesky.png' },
	// 		{ name: 'Shop 3', image: '/ocean.png' },
	// 		{ name: 'Shop 4', image: '/whilesnow.png' },
	// 		{ name: 'Shop 5', image: '/whilesnow.png' },
	// 		{ name: 'Shop 6', image: '/whilesnow.png' },
	// 		{ name: 'Shop 7', image: '/whilesnow.png' },
	// 		{ name: 'Shop 8', image: '/whilesnow.png' },
	// 		{ name: 'Shop 9', image: '/whilesnow.png' },
	// 		{ name: 'Shop 10', image: '/whilesnow.png' },
	//         { name: 'Shop 4', image: '/whilesnow.png' },
	//         { name: 'Shop 4', image: '/whilesnow.png' },
	//         { name: 'Shop 4', image: '/whilesnow.png' },
	//         { name: 'Shop 4', image: '/whilesnow.png' },
	//         { name: 'Shop 4', image: '/whilesnow.png' },
	//         { name: 'Shop 4', image: '/whilesnow.png' },
	//         { name: 'Shop 4', image: '/whilesnow.png' },
	//         { name: 'Shop 4', image: '/whilesnow.png' },
	//         { name: 'Shop 4', image: '/whilesnow.png' },
	//         { name: 'Shop 4', image: '/whilesnow.png' },
	//         { name: 'Shop 4', image: '/whilesnow.png' },
	//         { name: 'Shop 4', image: '/whilesnow.png' },
	//         { name: 'Shop 4', image: '/whilesnow.png' },
	//         { name: 'Shop 4', image: '/whilesnow.png' },
	//         { name: 'Shop 4', image: '/whilesnow.png' },
	// 		{ name: 'Shop 4', image: '/whilesnow.png' }
	// 	];
	// }

	//刷新页面背景
	function refreshBackgroundImage() {
		const body = document.querySelector('body');
		const timestamp = new Date().getTime();
		body.style.backgroundImage = `url('/whilesnow.png?timestamp=${timestamp}')`;
	}

	function showPage(page) {
		currentPage = page;
		if (page === 'profile') {
			getUserData();
		}
		if (page === 'shopcar') {
			fetchProducts();
		}
		if (page === 'dicussion'){
			fetchComments();
		}
	}

	// 以下是商城主页的逻辑
	// 获取所有商店的信息
	async function getShops() {
		try {
			const response = await fetch('/api/user/getshop', {
				method: 'POST',
				headers: {
					'Content-Type': 'application/json'
				}
			});
			if (!response.ok) {
				throw new Error(`HTTP error! status: ${response.status}`);
			}
			const data = await response.json();
			shops = Array.isArray(data) ? data : [data];
			// console.log(userData1[0]);
			if (shops[0] == null) {
				shops = [];
			}
		} catch (error) {
			console.error('Fetch error:', error);
		}
	}

	// 下面是个人信息页面的逻辑
	// 获取用户信息
	async function getUserData() {
		//console.log(userData);
		try {
			const response = await fetch('/api/user/userinfo', {
				method: 'POST',
				headers: {
					'Content-Type': 'application/json'
				},
				body: JSON.stringify({ username: userData.username })
			});
			if (!response.ok) {
				throw new Error(`HTTP error! status: ${response.status}`);
			}
			const data = await response.json();
			userData = data[0];
			//更新本地储存
			localStorage.setItem('userData', JSON.stringify(userData));
		} catch (error) {
			console.error('Fetch error:', error);
		}
	}
	// 用户表单等函数
	let isEditing = false;
	let editData;

	function editUserInfo() {
		editData = userData;
		isEditing = true;
	}

	function cancelEdit() {
		isEditing = false;
	}

	async function changeInfo() {
		// console.log(editData);
		try {
			const response = await fetch('/api/user/userinfo', {
				method: 'PUT',
				headers: {
					'Content-Type': 'application/json'
				},
				body: JSON.stringify({
					userType: editData.userType,
					username: editData.username,
					phonenumber: editData.phonenumber,
					idnumber: editData.idnumber,
					email: editData.email,
					password: editData.password
				})
			});
			if (!response.ok) {
				throw new Error(`HTTP error! status: ${response.status}`);
			}
			getUserData();
			cancelEdit();
			alert('更新信息成功');
		} catch (error) {
			alert('更新信息失败，请检查唯一性');
			console.error('Fetch error:', error);
			cancelEdit();
			editData = {};
			getUserData();
		}
	}

	//下面是购物车逻辑
	let products = [];
	let selectedProduct = null;
	let purchaseCount = 1;
	let totalPrice = 0;

	// products = [
	// 	{ shopname: 'Shop A', goodname: 'Good 1', goodprice: 100, goodcount: 10 },
	// 	{ shopname: 'Shop B', goodname: 'Good 2', goodprice: 200, goodcount: 5 },
	// 	{ shopname: 'Shop C', goodname: 'Good 3', goodprice: 150, goodcount: 8 }
	// ];

	// async function fetchProducts() {
	//     // 模拟的商品数据
	//     return [
	//         { shopname: 'Shop A', goodname: 'Good 1', goodprice: 100, goodcount: 10 },
	//         { shopname: 'Shop B', goodname: 'Good 2', goodprice: 200, goodcount: 5 },
	//         { shopname: 'Shop C', goodname: 'Good 3', goodprice: 150, goodcount: 8 }
	//     ];
	// }
	async function fetchProducts() {
		const response = await fetch('/api/user/getgood', {
			method: 'POST',
			headers: {
				'Content-Type': 'application/json'
			}
		});
		if (!response.ok) {
			throw new Error(`HTTP error! status: ${response.status}`);
		}
		const data = await response.json();
		products = Array.isArray(data) ? data : [data];
		console.log(products);
		if (products[0] == null) {
			products = [];
		}
	}

	function handlePurchase(product) {
		selectedProduct = product;
		purchaseCount = 1;
		calculateTotalPrice();
	}

	function calculateTotalPrice() {
		if (selectedProduct) {
			totalPrice = selectedProduct.goodprice * purchaseCount;
		}
	}

	async function confirmPurchase() {
		//console.log(purchaseCount);
		if (purchaseCount < 1 || purchaseCount > selectedProduct.goodcount) {
			alert('购买数量无效，请重新输入');
			return;
		}
		// 这里可以添加发送请求到后端的逻辑
		const response = await fetch('/api/user/goodbuy', {
			method: 'PUT',
			headers: {
				'Content-Type': 'application/json'
			},
			body: JSON.stringify({
				username: userData.username,
				shopname: selectedProduct.shopname,
				goodname: selectedProduct.goodname,
				goodprice: selectedProduct.goodprice,
				goodcount: purchaseCount,
				cost: selectedProduct.goodprice * purchaseCount * 1.0
			})
		});
		if (!response.ok) {
			throw new Error(`HTTP error! status: ${response.status}`);
		}
		alert('正在支付中，请稍等...');
		alert(`购买成功：${selectedProduct.goodname} 数量：${purchaseCount}`);
		selectedProduct = null;
		fetchProducts();
	}

	function cancelPurchase() {
		selectedProduct = null;
	}

	// 下面是用户评论逻辑
	// 获取当前时间的函数，并格式化为 PostgreSQL 日期格式
	function getCurrentTime() {
		const now = new Date();
		const year = now.getFullYear();
		const month = (now.getMonth() + 1).toString().padStart(2, '0');
		const day = now.getDate().toString().padStart(2, '0');
		const hours = now.getHours().toString().padStart(2, '0');
		const minutes = now.getMinutes().toString().padStart(2, '0');
		const seconds = now.getSeconds().toString().padStart(2, '0');
		currentTime = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
	}

	// 新的变量，用于评论表单
	let showCommentForm = false;
	let commentProduct = null;
	let commentText = '';

	function handleComment(product) {
		showCommentForm = true;
		commentProduct = product;
	}

	function cancelComment() {
		showCommentForm = false;
		commentProduct = null;
		commentText = '';
	}

	async function submitComment() {
		// 这里是提交评论的逻辑，可以是一个空函数
		try {
			getCurrentTime();
			const response = await fetch('/api/user/commentgive', {
				method: 'POST',
				headers: {
					'Content-Type': 'application/json'
				},
				body: JSON.stringify({
					username: userData.username,
					shopname: commentProduct.shopname,
					goodname: commentProduct.goodname,
					text: commentText,
					time: currentTime
				})
			});
			if (!response.ok) {
				throw new Error(`HTTP error! status: ${response.status}`);
			}
			alert('评论成功!');
		} catch (error) {
			console.error('Fetch error:', error);
		}
		cancelComment();
	}



	// 下面是评论系统的逻辑
	let commentData = [];

	// 获取评论
	async function fetchComments() {
		const response = await fetch('/api/user/commentget', {
			method: 'POST',
			headers: {
				'Content-Type': 'application/json'
			}
		});
		if (!response.ok) {
			throw new Error(`HTTP error! status: ${response.status}`);
		}
		
		const data = await response.json();
		commentData = Array.isArray(data) ? data : [data];
		console.log(commentData);
		if (commentData[0] == null) {
			commentData = [];
		}
	}

</script>

<div class="sidebar">
	<button on:click={() => showPage('shop')}>商城主页</button>
	<button on:click={() => showPage('profile')}>个人信息</button>
	<button on:click={() => showPage('shopcar')}>购物车</button>
	<button on:click={() => showPage('dicussion')}>评论系统</button>
</div>

<div class="content">
	{#if currentPage === 'shop'}
		<h1>商城主页</h1>
		<div class="shop-grid">
			{#each shops as shop}
				<ShopItem shopName={shop.shopname} shopImage={'/shopimage/' + shop.imagename} />
			{/each}
		</div>
	{:else if currentPage === 'profile'}
		<h1>个人信息</h1>
		<h2>欢迎您，{userData.username}</h2>
		<!-- 表格展示用户数据 -->
		<table class="profile-table">
			<thead>
				<tr>
					<th>UserType</th>
					<th>Username</th>
					<th>Phonenumber</th>
					<th>Idnumber</th>
					<th>Email</th>
					<th>Password</th>
					<th>Option</th>
				</tr>
			</thead>
			<tbody>
				<tr>
					<td>{userData.userType}</td>
					<td>{userData.username}</td>
					<td>{userData.phonenumber}</td>
					<td>{userData.idnumber}</td>
					<td>{userData.email}</td>
					<td>{userData.password}</td>
					<td><button class="edit-button" on:click={editUserInfo}>修改</button></td>
				</tr>
			</tbody>
		</table>

		{#if isEditing}
			<div class="overlay {isEditing ? 'visible' : ''}">
				<div class="edit-form-container {isEditing ? 'open' : ''}">
					<form>
						<div class="form-group">
							<label for="userType">UserType</label>
							<input type="text" id="userType" value={editData.userType} readonly />
						</div>
						<div class="form-group">
							<label for="username">Username</label>
							<input type="text" id="username" value={editData.username} readonly />
						</div>
						<div class="form-group">
							<label for="phoneNumber">Phonenumber</label>
							<input type="text" id="phoneNumber" bind:value={editData.phonenumber} />
						</div>
						<div class="form-group">
							<label for="idNumber">Idnumber</label>
							<input type="text" id="idNumber" value={editData.idnumber} readonly />
						</div>
						<div class="form-group">
							<label for="email">Email</label>
							<input type="email" id="email" bind:value={editData.email} />
						</div>
						<div class="form-group">
							<label for="password">Password</label>
							<input type="password" id="password" bind:value={editData.password} />
						</div>
						<div class="form-buttons">
							<button type="button" class="submit-button" on:click={changeInfo}>提交</button>
							<button type="button" class="cancel-button" on:click={cancelEdit}>取消</button>
						</div>
					</form>
				</div>
			</div>
		{/if}
	{:else if currentPage === 'shopcar'}
		<h1>购物车</h1>

		<table class="buy-table">
			<thead>
				<tr>
					<th class="buy-th">Shopname</th>
					<th class="buy-th">Goodname</th>
					<th class="buy-th">Goodprice</th>
					<th class="buy-th">Goodcount</th>
					<th class="buy-th">Action</th>
				</tr>
			</thead>
			<tbody>
				{#each products as product}
					<tr>
						<td class="buy-td">{product.shopname}</td>
						<td class="buy-td">{product.goodname}</td>
						<td class="buy-td">{product.goodprice}</td>
						<td class="buy-td">{product.goodcount}</td>
						<td class="buy-td">
							<button class="buy-button buy-buy-btn" on:click={() => handlePurchase(product)}
								>购买</button
							>
							<button class="buy-button comment-button" on:click={() => handleComment(product)}
								>评论</button
							>
						</td>
					</tr>
				{/each}
				{#if products.length === 0}
					<tr>
						<td colspan="5">No elem found</td>
					</tr>
				{/if}
			</tbody>
		</table>

		{#if selectedProduct}
			<div class="buy-form-container">
				<label>Username: <input type="text" value={userData.username} readonly /></label>
				<label>Shopname: <input type="text" value={selectedProduct.shopname} readonly /></label>
				<label>Goodname: <input type="text" value={selectedProduct.goodname} readonly /></label>
				<label>Goodprice: <input type="number" value={selectedProduct.goodprice} readonly /></label>
				<label
					>Count: <input
						type="number"
						bind:value={purchaseCount}
						min="1"
						max={selectedProduct.goodcount}
						on:input={calculateTotalPrice}
						required
					/></label
				>
				<label>Total Price: <input type="number" value={totalPrice} readonly /></label>
				<div class="buy-button-group">
					<button class="buy-button buy-confirm-btn" on:click={confirmPurchase}>确认</button>
					<button class="buy-button buy-cancel-btn" on:click={cancelPurchase}>取消</button>
				</div>
			</div>
		{/if}

		{#if showCommentForm}
			<div class="comment-form-container">
				<table class="comment-table">
					<tr>
						<td>Username:</td>
						<td><input type="text" value={userData.username} readonly /></td>
					</tr>
					<tr>
						<td>Shopname:</td>
						<td><input type="text" value={commentProduct.shopname} readonly /></td>
					</tr>
					<tr>
						<td>Goodname:</td>
						<td><input type="text" value={commentProduct.goodname} readonly /></td>
					</tr>
					<tr>
						<td>Comment:</td>
						<td><textarea bind:value={commentText} required></textarea></td>
					</tr>
					<tr>
						<td colspan="2">
							<div class="comment-button-group">
								<button class="comment-button comment-submit-btn" on:click={submitComment}
									>提交</button
								>
								<button class="comment-button comment-cancel-btn" on:click={cancelComment}
									>取消</button
								>
							</div>
						</td>
					</tr>
				</table>
			</div>
		{/if}
	{:else if currentPage === 'dicussion'}
		<h1>评论系统</h1>
		<table class="profile-table">
			<thead>
				<tr>
					<th>Time</th>
					<th>Username</th>
					<th>Shopname</th>
					<th>Goodname</th>
					<th>Comment</th>
				</tr>
			</thead>
			<tbody>
				{#each commentData as comment}
					<tr>
						<td>{comment.time}</td>
						<td>{comment.username}</td>
						<td>{comment.shopname}</td>
						<td>{comment.goodname}</td>
						<td>{comment.text}</td>
					</tr>
				{/each}
				{#if commentData.length === 0}
					<tr>
						<td colspan="5">No elem found</td>
					</tr>
				{/if}
			</tbody>
		</table>
	{/if}
</div>

<style>
	/* 下面是侧边栏以及商城主页的CSS样式 */
	.sidebar {
		width: 30px; /* 初始宽度 */
		background: #ea88b4;
		color: #fff;
		padding: 10px;
		position: fixed;
		height: 100%;
		transition: width 0.3s;
	}
	.sidebar:hover {
		width: 200px; /* 鼠标悬停时宽度 */
	}
	.sidebar button {
		display: block;
		width: 100%;
		padding: 10px;
		margin-bottom: 10px;
		background: #38d8ea;
		border: none;
		color: white;
		cursor: pointer;
		text-align: left; /* 按钮文本左对齐 */
	}
	.content {
		margin-left: 70px; /* 调整为初始侧边栏宽度+10px的margin */
		padding: 20px;
		transition: margin-left 0.3s;
	}
	.sidebar:hover ~ .content {
		margin-left: 210px; /* 鼠标悬停时的margin */
	}
	.shop-grid {
		display: grid;
		grid-template-columns: repeat(auto-fill, minmax(200px, 1fr)); /* 自动填充，每列最小200px */
		gap: 20px; /* 网格间距 */
	}

	/* 下面是个人主页的CSS样式 */
	/* body {
		overflow-x: hidden; /* 防止页面横向滚动 */
	/*} */

	.profile-table {
		width: 100%;
		border-collapse: collapse;
		margin-top: 20px;
	}

	.profile-table th,
	.profile-table td {
		border: 1px solid #ddd;
		padding: 8px;
		text-align: center;
	}

	.profile-table th {
		background-color: #f2f2f2;
	}

	.profile-table tbody tr:nth-child(even) {
		background-color: #f2f2f2;
	}

	.profile-table tbody tr:hover {
		background-color: #e0e0e0;
	}

	.edit-button {
		background-color: #007bff;
		color: white;
		border: none;
		padding: 8px 12px;
		border-radius: 4px;
		cursor: pointer;
		transition: background-color 0.3s;
	}

	.edit-button:hover {
		background-color: #0056b3;
	}

	.overlay {
		position: fixed;
		top: 0;
		right: -100%;
		width: 30%;
		height: 100%;
		background: rgba(0, 0, 0, 0.5);
		transition: right 0.3s ease-in-out;
		z-index: 1000;
	}

	.overlay.visible {
		right: 0;
	}

	.edit-form-container {
		background: white;
		height: 100%;
		padding: 20px;
		box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
	}

	.form-group {
		margin-bottom: 15px;
	}

	.form-group label {
		display: block;
		margin-bottom: 5px;
	}

	.form-group input {
		width: 100%;
		padding: 8px;
		border: 1px solid #ddd;
		border-radius: 4px;
	}

	.form-buttons {
		display: flex;
		justify-content: space-between;
	}

	.submit-button {
		background-color: #28a745;
		color: white;
		border: none;
		padding: 8px 12px;
		border-radius: 4px;
		cursor: pointer;
		transition: background-color 0.3s;
	}

	.submit-button:hover {
		background-color: #218838;
	}

	.cancel-button {
		background-color: #dc3545;
		color: white;
		border: none;
		padding: 8px 12px;
		border-radius: 4px;
		cursor: pointer;
		transition: background-color 0.3s;
	}

	.cancel-button:hover {
		background-color: #c82333;
	}

	/* 下面是购物车系统的css样式 */
	/* .buy-h1 {
		text-align: center;
		margin-bottom: 20px;
	} */
	.buy-table {
		width: 100%;
		border-collapse: collapse;
		margin-bottom: 20px;
	}
	.buy-th,
	.buy-td {
		border: 1px solid #ddd;
		padding: 8px;
		text-align: left;
	}
	.buy-th {
		background-color: #f4f4f4;
	}
	.buy-button-group {
		display: flex;
		justify-content: space-between;
		margin-top: 10px;
	}
	.buy-button {
		padding: 8px 12px;
		border: none;
		cursor: pointer;
		border-radius: 4px;
	}
	.buy-buy-btn {
		background-color: #007bff;
		color: white;
	}
	.buy-confirm-btn {
		background-color: #28a745;
		color: white;
	}
	.buy-cancel-btn {
		background-color: #dc3545;
		color: white;
	}
	.buy-form-container {
		border: 1px solid #ddd;
		padding: 20px;
		border-radius: 8px;
		background-color: #f9f9f9;
	}
	.buy-form-container label {
		display: block;
		margin-bottom: 10px;
	}
	.buy-form-container input {
		width: 100%;
		padding: 8px;
		margin-bottom: 10px;
		border: 1px solid #ccc;
		border-radius: 4px;
	}

	.comment-form-container {
		position: fixed;
		top: 50%;
		left: 50%;
		transform: translate(-50%, -50%);
		background-color: white;
		padding: 20px;
		border: 1px solid #ccc;
		box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
		z-index: 1000;
		width: 400px;
		display: flex;
		flex-direction: column;
		gap: 10px;
	}

	.comment-table {
		width: 100%;
		border-collapse: collapse;
	}

	.comment-table td {
		padding: 10px;
		border: 1px solid #ddd;
	}

	.comment-table input,
	.comment-table textarea {
		width: 100%;
		padding: 8px;
		border: 1px solid #ccc;
		border-radius: 4px;
		box-sizing: border-box;
	}

	.comment-table textarea {
		resize: vertical;
	}

	.comment-button-group {
		display: flex;
		justify-content: space-between;
	}

	.comment-button {
		background-color: #ea88b4;
		color: white;
	}

	.comment-button:hover {
		background-color: #e4678a;
	}

	.comment-submit-btn {
		background-color: blue;
		color: white;
	}

	.comment-cancel-btn {
		background-color: red;
		color: white;
	}
</style>
